package fr.sportcom.sportcom.services;

import fr.sportcom.sportcom.R;
import fr.sportcom.sportcom.controller.EventDetailActivity;
import fr.sportcom.sportcom.model.CEvent;
import android.app.IntentService;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

/**
 * An {@link IntentService} subclass for handling asynchronous task requests in
 * a service on a separate handler thread.
 * <p>
 * TODO: Customize class - update intent actions, extra parameters and static
 * helper methods.
 */
public class ProcessAlarmNotifyIntentService extends IntentService {
	
	private final static String TAG_SERVICE = "fr.sportcom.sportcom.tag.ProcessAlarmNotifyIntentService";
	private final static String EXTRA_STARTED = "fr.sportcom.sportcom.extra.service.recalarm.STARTED";
	private final static String EXTRA_EVENT = "fr.sportcom.sportcom.extra.service.recalarm.EVENT";
	
	public int ID_NOTIFICATION = 20;

	public static PendingIntent prepareIntent(Context context, CEvent event, boolean start) {
		Intent i = new Intent(context, ProcessAlarmNotifyIntentService.class);
		i.putExtra(EXTRA_EVENT, event);
		i.putExtra(EXTRA_STARTED, start);
		return PendingIntent.getService(context, 700, i, PendingIntent.FLAG_UPDATE_CURRENT);
	}

	public ProcessAlarmNotifyIntentService() {
		super(TAG_SERVICE);
	}

	@Override
	protected void onHandleIntent(Intent intent) {
		CEvent event = intent.getParcelableExtra(EXTRA_EVENT);
		boolean started = intent.getBooleanExtra(EXTRA_STARTED, false);
		
		generateNotification(event, started);
	}
	

	@SuppressWarnings("deprecation")
	private void generateNotification(CEvent event, boolean started) {
		// L'ic�ne sera une petite loupe
		int icon = R.drawable.alarm;
		// Icone large
		Bitmap bmIco = BitmapFactory.decodeResource(getResources(), R.drawable.alarm);
		// Le premier titre affich�
		String title = "Titre";
		if(started) {
			title = "Evenement en cours";
		}
		else {
			title = "Début à " + event.getStrBHour();
		}
		// L'intent
		PendingIntent intent = EventDetailActivity.prepareIntent(this, event);
		
		// La notification est créée
		Notification noti = new Notification.Builder(this)
	        .setContentTitle(title)
	        .setContentText(title)
	        .setSmallIcon(icon)
	        .setLargeIcon(bmIco)
	        .setContentIntent(intent)
	        .setAutoCancel(true)
	        .getNotification();
		
		// R�cup�ration du Notification Manager
		NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
		
		manager.notify(ID_NOTIFICATION+event.getId(), noti);
	}
}
